package idv.arthur.svn;

import idv.arthur.structures.I1S1;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.tmatesoft.svn.core.ISVNDirEntryHandler;
import org.tmatesoft.svn.core.SVNCommitInfo;
import org.tmatesoft.svn.core.SVNDirEntry;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNNodeKind;
import org.tmatesoft.svn.core.SVNProperties;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager;
import org.tmatesoft.svn.core.internal.wc.DefaultSVNOptions;
import org.tmatesoft.svn.core.io.ISVNEditor;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.tmatesoft.svn.core.io.diff.SVNDeltaGenerator;
import org.tmatesoft.svn.core.wc.SVNClientManager;
import org.tmatesoft.svn.core.wc.SVNLogClient;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNWCUtil;

public class CopyAP2CM {
	
	static List<I1S1> fileList = new ArrayList<I1S1>();
	
	public static void main(String[] args) throws SVNException, IOException {
		String url = "http://10.144.97.99/Arthur/branch/20140509_09/";
		SVNClientManager manager;
		SVNURL repositoryBaseUrl;
		ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
		InputStream input = null;
		manager = SVNClientManager.newInstance(new DefaultSVNOptions(), "Arthur", "arthur7382"); // 如果需要用戶名密碼
		try {
			repositoryBaseUrl = SVNURL.parseURIEncoded(url); // 傳入svn地址
			SVNLogClient logClient = manager.getLogClient();
			ISVNDirEntryHandler handler = new FileEntryHandler();
			
			fileList.clear();
			
			logClient.doList(repositoryBaseUrl, SVNRevision.HEAD, SVNRevision.HEAD,false, true, handler); // 列出當前svn地址的目錄，對每個文件進行處理
			
			System.out.println("Size:"+fileList.size());
			System.out.println();
			System.out.println();
			System.out.println();
			System.out.println("全部簽去SVN CM");
			
			String cmUrl = "http://10.144.97.99/gamma";
			String cmPwd = "abcd1234";
			String cmId = "gamma";
			String apUrl = "http://10.144.97.99/Arthur";
			String apPwd = "arthur7382";
			String apId = "Arthur";
			SVNRepository cmRepo = SVNRepositoryFactory.create(SVNURL.parseURIEncoded(cmUrl));
			ISVNAuthenticationManager authManager = SVNWCUtil.createDefaultAuthenticationManager(cmId, cmPwd);
	        cmRepo.setAuthenticationManager(authManager);
	        SVNRepository apRepo = SVNRepositoryFactory.create(SVNURL.parseURIEncoded(apUrl));
	        apRepo.setAuthenticationManager(authManager);
	        authManager = SVNWCUtil.createDefaultAuthenticationManager(apId, apPwd);
	        
	        SVNDeltaGenerator deltaGenerator = new SVNDeltaGenerator();
            String logMessage = "Created at："+System.currentTimeMillis();	//在Commit時送出的Message
            ISVNEditor editor = null;
            SVNCommitInfo info = null;
            
            editor = cmRepo.getCommitEditor(logMessage, new CommitMediator() );
            editor.openRoot(-1);
            SVNProperties properties = new SVNProperties();
            
            
            for(int i=0; i<CopyAP2CM.fileList.size();i++) {
            	I1S1 is = CopyAP2CM.fileList.get(i);
            	String cmPath = "";
            	String[] pathArray = is.getS1().split("/");	//記錄這個檔案延途的路徑
            	int numberCloseDir = pathArray.length; //這是給SVN CM用的，算階層的(目前這行是先以Dir來看)，用以回到根節點
            	System.out.println("次數："+numberCloseDir);
            	if( is.getI1() == 0 ) {	//表示是資料夾
            		System.out.println("這個是資料夾："+is.getS1());
            		for(int j=0; j<numberCloseDir ;j++ ) {
            			cmPath += pathArray[j]+"/";	//這是給 SVN AP用的，抓資料的路徑
            			String path = cmPath.substring(0, cmPath.length()-1);
            			System.out.println("目前處理："+path);
            			try {
            				editor.addDir( path, null , -1 );
            	        	System.out.println("路徑："+path+"，不存在==>創建");
            	        } catch(Exception e) {
            	        	System.out.println("路徑："+path+"，存在");
            	        }
            		}
            		for(int j=0; j<numberCloseDir ;j++ ) {
            			editor.closeDir();
            		}
            	} else {	//表示是檔案
            		numberCloseDir--;
            		String fn = pathArray[numberCloseDir];
            		System.out.println("這個是檔案："+is.getS1()+",要close的次數"+numberCloseDir);
            		
            		//先用切換到它所該在的路徑下
            		for(int j=0; j<numberCloseDir ;j++ ) {
            			cmPath += pathArray[j]+"/";	//這是給 SVN AP用的，抓資料的路徑
            			System.out.println("目前處理："+pathArray[j]);
            			String path = cmPath.substring(0, cmPath.length()-1);
            			try {
            				editor.addDir( path, null , -1);
            	        	System.out.println("路徑："+pathArray[j]+"，不存在==>創建");
            	        } catch(SVNException e) {
            	        	System.out.println("路徑："+pathArray[j]+"，存在==>進入");
            	        }
            		}
            		cmPath += fn;
            		System.out.println("檔案名稱:"+fn+"\n");
            		apRepo.getFile( "branch/20140509_09/"+is.getS1(),SVNRevision.HEAD.getNumber(), properties, baos);
  			        input  = new ByteArrayInputStream( baos.toByteArray() );
            		try {
            			editor.addFile( is.getS1(), null , -1 );
        	        } catch(SVNException e) {
        	        	editor.openFile( is.getS1(), -1);	
        	        }
            		editor.applyTextDelta( is.getS1(), null); 
    	    		String baseChecksum = deltaGenerator.sendDelta( is.getS1(), input, editor, true);
    	    	    editor.textDeltaEnd( is.getS1() );
    	    	    editor.closeFile( is.getS1(), baseChecksum );
    	    	    
    	    	    for(int j=0; j<numberCloseDir ;j++ ) {
            			editor.closeDir();
            		}
            	}
            }
            
            info = editor.closeEdit();
            System.out.println("結束了，目標版次是："+info.getNewRevision());
		} catch (SVNException e) {
			e.printStackTrace();
		} finally {
			if ( input != null ) { input.close(); }
			if ( baos != null ) { baos.close(); }
			manager.dispose();
		}
		
		//取得帳密 ( 4G演算法 )
		
		//複制該資料夾下的的一切，到CM 的repo中
		
		//簽入 SVN CM
		
		
		
    	
	}
	
	public static void chg(String finalDir,String currentDir) {
		
		if( !finalDir.equalsIgnoreCase(currentDir) ) {
			char[] finalArray = finalDir.toCharArray();
			char[] currentArray = currentDir.toCharArray();
			String path = "";
			int sizeArray = Math.min(finalArray.length,currentArray.length);
			for( int i=0; i<sizeArray;i++ ) {
				if( finalArray[i] == currentArray[i] ) {
					path += finalArray[i];
				} else {
					break;
				}
			}
			String tailStr = currentDir.substring(path.length(), currentDir.length());
			if( finalDir.length() > currentDir.length() ) {
				System.out.print("需上移"+tailStr.split("/").length+"次, ");	
			} else {
				System.out.print("需下切"+tailStr.split("/").length+"次, ");
			}
			
			
			System.out.println("切換到："+path);
		}

	}

}

class FileEntryHandler implements ISVNDirEntryHandler {
	public void handleDirEntry(SVNDirEntry entry) throws SVNException {
		I1S1 is = new I1S1();
		
		if ( entry.getKind() == SVNNodeKind.DIR ) {
			if ( !"".equalsIgnoreCase(entry.getRelativePath()) ) {
				is.setI1(0);
				is.setS1( entry.getRelativePath() );
				CopyAP2CM.fileList.add( is );
				System.out.println( entry.getKind()+"\t"+entry.getRelativePath()+", "+CopyAP2CM.fileList.size());
			}
		} else if ( entry.getKind() == SVNNodeKind.FILE ) {
			is.setI1(1);
			is.setS1( entry.getRelativePath() );
			CopyAP2CM.fileList.add( is );
			System.out.println( entry.getKind()+"\t"+entry.getRelativePath()+", "+CopyAP2CM.fileList.size());
		}
	}
}


